package com.ls.herostory.cmdhandler;

import com.ls.herostory.login.UserManager;
import com.ls.herostory.msg.GameMsgProtocol;
import com.ls.herostory.session.SessionUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author liangsu
 * @version v1.0
 * @Description
 * @Date 2020/10/14 9:08
 * @since
 */
public class UserLoginCmdHandler implements CmdHandler<GameMsgProtocol.UserLoginCmd> {

    private final static Logger logger = LoggerFactory.getLogger(UserLoginCmdHandler.class);

    @Override
    public void handleCmd(ChannelHandlerContext ctx, GameMsgProtocol.UserLoginCmd cmd) {

        UserManager.getInstance().asyncLogin(cmd.getUserName(), cmd.getPassword(), (user) ->{

            GameMsgProtocol.UserLoginResult.Builder builder = GameMsgProtocol.UserLoginResult.newBuilder();
            if(user != null){ //
                builder.setUserId(user.getId())
                        .setUserName(user.getUserName())
                        .setHeroAvatar(user.getHeroAvatar());

                // 创建回话
                SessionUtil.createSession(user, (NioSocketChannel) ctx.channel());

            }else{ // 登陆失败
                builder.setUserId(-1)
                        .setUserName("")
                        .setHeroAvatar("");
            }

            GameMsgProtocol.UserLoginResult userLoginResult = builder.build();
            ctx.writeAndFlush(userLoginResult);
        });

    }


}
